package logic

import (
	"2211a_mayi/service/internal/svc"
	"2211a_mayi/service/mayi"
	"2211a_mayi/service/models"
	"2211a_mayi/service/pkg"
	"context"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *mayi.LoginRequest) (*mayi.LoginResponse, error) {
	var user models.User
	var err error
	err = user.FindByUsername(in.Username)
	if err != nil {
		return nil, err
	}
	// 判断是否存在
	if user.ID == 0 {
		// 不存在,注册
		user.Username = in.Username
		user.Password = pkg.Md5(in.Password)
		err = user.Create()
		if err != nil {
			logx.Error(err)
			return nil, err
		}
	} else {
		// 存在,判断密码是否正确
		if user.Password != pkg.Md5(in.Password) {
			logx.Error("密码错误")
			return nil, errors.New("密码错误")
		}
	}

	return &mayi.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
